﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;
using Agile.Engine.Utils;

namespace Fis.Win.Forms
{
    public partial class BillExtraForm : BaseForm
    {
        public BillExtraForm()
        {
            InitializeComponent();

            #region Lookup Registe

            registry["0"] = lookUpEdit0;
            registry["1"] = lookUpEdit1;
            registry["2"] = lookUpEdit2;
            registry["3"] = lookUpEdit3;
            registry["4"] = lookUpEdit4;
            registry["5"] = lookUpEdit5;
            registry["6"] = lookUpEdit6;
            registry["7"] = lookUpEdit7;
            registry["8"] = lookUpEdit8;
            #endregion

        }

        /// <summary>
        /// 科目
        /// </summary>
        public DataRow Account { get; set; }
        /// <summary>
        /// 凭证明细行
        /// </summary>
        public DataRow BillDetail { get; set; }
        /// <summary>
        /// 方向
        /// </summary>
        public int BillDirect { get; set; }

        public override string Message
        {
            get
            {
                return lcMessage.Text;
            }
            set
            {
                lcMessage.Text = value;
            }
        }

        Dictionary<string, DevExpress.XtraEditors.LookUpEdit> registry
            = new Dictionary<string, DevExpress.XtraEditors.LookUpEdit>();

        public override void InitializeBinding()
        {
            ///外币核算
            edDefault.EditValue = Agile.Engine.Utils.DataUtils.Parse(0m, BillDetail[(BillDirect == 1) ? "FDEBITAMOUNT" : "FCREDITAMOUNT"]);
            edAmount.DataBindings.Add("Value", edDefault, "Value");

            if (groupRate.Enabled)
            {
                var rateRow = CacheContext.GetCache("TRATE").Select(string.Format("SID='{0}'", Account["FBZ"]))[0];
                lbWB.Text = rateRow["FNAME"].ToString();
                edRate.EditValue = Agile.Engine.Utils.DataUtils.Parse(0m, BillDetail["FRATE"]);
                if (edRate.Value == 0)
                    edRate.EditValue = BillDetail["FRATE"] = rateRow["FRATE"];

                edCurrency.EditValue = Agile.Engine.Utils.DataUtils.Parse(0m, BillDetail[(BillDirect == 1) ? "FCURRENCYDEBIT" : "FCURRENCYCREDIT"]);
                if (edCurrency.Value == 0)
                    edCurrency.Value = (edRate.Value == 0) ? 0 : edDefault.Value / edRate.Value;
            }

            ///数量
            if (groupNumber.Enabled)
            {
                edQuantity.EditValue = Agile.Engine.Utils.DataUtils.Parse(0m, BillDetail[(BillDirect == 1) ? "FQUANTITYDEBIT" : "FQUANTITYCREDIT"]);
                edPrice.EditValue = Agile.Engine.Utils.DataUtils.Parse(0m, BillDetail["FUNITPRICE"]);
            }

            ///辅助核算
            if (groupAids.Enabled)
            {
                var info = BillDetail["FHSVALUE"].ToString();
                foreach (var i in registry.AsEnumerable())
                {
                    var s = CacheContext.GetCache("TAIDS").Select(string.Format("FGROUP='{0}'", i.Key));
                    if (s.Length > 0)
                    {
                        var binding = s.CopyToDataTable();
                        UIUtils.LookUpBinding(i.Value, binding, "FNAME", "SID");
                        if (!string.IsNullOrEmpty(info))
                            i.Value.EditValue = info.Substring(info.IndexOf(i.Key + ":") + 2, 36);
                        else
                        {
                            var defaultAids = binding.Select("FDEFAULT=1");
                            if (defaultAids.Length > 0)
                                i.Value.EditValue = defaultAids[0]["SID"];
                        }
                    }
                }
            }

        }

        public override void InitializeViewUI()
        {
            groupNumber.Enabled = (Account["FQUANTITY"].ToString() == "1");
            groupRate.Enabled = (Account["FBZ"].ToString() != CacheContext.DefaultCurrencyRate);
            if (groupRate.Enabled)
                lbWB.Text = CacheContext.GetCache("TRATE").Select(string.Format("SID='{0}'", Account["FBZ"]))[0]["FNAME"].ToString();

            //辅助核算
            if (Agile.Engine.Utils.StringUtils.IsEmpty(Account["FFZHS"]))
            {
                groupAids.Enabled = false;
                groupAids.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                return;
            }

            for (var i = 0; i < 9; i++)
            {
                var item = layoutControl1.GetItemByControl(registry[i.ToString()]);

                if (Account["FFZHS"].ToString().IndexOf(i.ToString()) >= 0)
                {
                    var r = CacheContext.GetCache("aidsgroup").Select(string.Format("key='{0}'", i))[0];
                    var key = r["key"].ToString();
                    var caption = r["caption"].ToString();

                    item.Text = caption;
                    item.CustomizationFormText = caption;
                    var edit = registry[i.ToString()];
                    edit.Tag = key;

                }
                else
                {
                    layoutControl1.HideItem(item);
                    registry.Remove(i.ToString());
                }
            }


        }

        void edit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                var edit = (sender as DevExpress.XtraEditors.LookUpEdit);

                System.Collections.Hashtable m = new System.Collections.Hashtable();
                m["FGROUP"] = edit.Tag;

                var v = UIManager.ShowEdit<AidsEditForm>("AidsEditViewProvider", Agile.Engine.View.ViewState.AddNew, m);
                if (Agile.Engine.Utils.DataUtils.Parse(DialogResult.Cancel, v.ViewResult) == System.Windows.Forms.DialogResult.OK)
                {
                    CacheContext.RefreshCache(v.ViewProvider.DataTableName);
                    var s = CacheContext.GetCache("TAIDS").Select(string.Format("FGROUP='{0}'", edit.Tag));
                    if (s.Length > 0)
                    {
                        UIUtils.LookUpBinding(edit, s.CopyToDataTable(), "FNAME", "SID", (v.ViewModel["viewData"] as DataTable).Rows[0]["SID"]);
                    }

                }
            }
        }

        private void BillExtraForm_Load(object sender, EventArgs e)
        {
            InitializeViewUI();
            InitializeBinding();
        }

        private void bnOK_Click(object sender, EventArgs e)
        {
            #region Result

            BillDetail[(BillDirect == 1) ? "FDEBITAMOUNT" : "FCREDITAMOUNT"] = edDefault.Value;
            BillDetail["FRATE"] = edRate.Value;
            BillDetail[(BillDirect == 1) ? "FCURRENCYDEBIT" : "FCURRENCYCREDIT"] = edCurrency.Value;
            BillDetail[(BillDirect == 1) ? "FQUANTITYDEBIT" : "FQUANTITYCREDIT"] = edQuantity.Value;
            BillDetail["FUNITPRICE"] = edPrice.Value;

            if (groupAids.Enabled)
            {
                var fzhs = from i in registry.AsEnumerable()
                           select string.Format("{0}:{1}", i.Key, i.Value.EditValue);

                BillDetail["FHSVALUE"] = string.Join(",", fzhs.ToArray());
            }
            #endregion


            DialogResult = System.Windows.Forms.DialogResult.OK;
            Close();
        }

        private void bnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        bool ValidateBeforeClose()
        {
            //汇率
            if (groupRate.Enabled)
            {
                if (IsZeroValue(edCurrency))
                {
                    Message = "外币不能为0";
                    return false;
                }

                if (IsZeroValue(edRate))
                {
                    Message = "汇率不能为0";
                    return false;
                }

            }

            if (groupNumber.Enabled)
            {
                if (IsZeroValue(edQuantity))
                {
                    Message = "数量不能为0";
                    return false;
                }
                if (IsZeroValue(edPrice))
                {
                    Message = "数量不能为0";
                    return false;
                }
            }

            if (groupNumber.Enabled && groupRate.Enabled && edDefault.Value != edAmount.Value)
            {
                Message = "本位币金额必须和数量金额一致";
                return false;
            }

            if (groupAids.Enabled)
            {

                foreach (var i in registry.AsEnumerable())
                {
                    if (StringUtils.IsEmpty(i.Value.EditValue))
                    {
                        var item = layoutControl1.GetItemByControl(i.Value);
                        Message = "请选择" + item.Text;
                        return false;
                    }
                }
            }

            Message = string.Empty;
            return true;
        }

        bool IsZeroValue(DevExpress.XtraEditors.SpinEdit edit)
        {
            if (edit.Value == 0)
            {
                edit.Focus();
                return true;
            }
            return false;
        }

        private void edDefault_EditValueChanged(object sender, EventArgs e)
        {

            if (!edDefault.EditorContainsFocus)
                return;

            edCurrency.Value = (edRate.Value == 0) ? 0 : edDefault.Value / edRate.Value;

        }

        private void edCurrency_EditValueChanged(object sender, EventArgs e)
        {
            if (!edCurrency.EditorContainsFocus)
                return;

            edDefault.Value = edCurrency.Value * edRate.Value;
        }

        private void edRate_EditValueChanged(object sender, EventArgs e)
        {
            if (!edRate.EditorContainsFocus)
                return;

            if (edRate.Value != 0)
                edDefault.Value = edCurrency.Value * edRate.Value;

        }

        private void edQuantity_EditValueChanged(object sender, EventArgs e)
        {
            if (!edQuantity.EditorContainsFocus)
                return;

            edAmount.Value = edQuantity.Value * edPrice.Value;
        }

        private void edPrice_EditValueChanged(object sender, EventArgs e)
        {
            if (!edPrice.EditorContainsFocus)
                return;

            edAmount.Value = edQuantity.Value * edPrice.Value;

        }

        private void edAmount_EditValueChanged(object sender, EventArgs e)
        {
            if (!edAmount.EditorContainsFocus)
                return;

            edQuantity.Value = (edPrice.Value == 0) ? 0 : edAmount.Value / edPrice.Value;
        }

        private void lookUpEdit_Enter(object sender, EventArgs e)
        {
            SendKeys.Send("{F4}");
        }
    }
}
